<template>
  <div
    id="goodList"
    class="good-list"
    :style="{
      height:
        oldHeight.top > newHeight.top
          ? oldHeight.top + 'px'
          : newHeight.top + 'px',
    }"
  >
    <div
      class="good-item"
      :style="heightArr[key]"
      v-for="(item, key) in banner"
      :key="item.name"
      v-show="goods.length"
    >
      <slot :name="item.name"></slot>
    </div>
    <div
      class="good-item"
      :style="heightArr[index + banner.length]"
      v-for="(value, index) in goods"
      :key="index"
    >
      <slot :value="value"> </slot>
    </div>
  </div>
</template>
<script>
import { toRefs, reactive } from "vue";
export default {
  name: "product",
  props: {
    goods: {
      type: Object,
    },
    banner: {
      type: Object,
    },
  },
  setup(props) {
    const data = reactive({
      heightArr: [
        { top: "0px", left: 0 },
        { top: "0px", left: "50%" },
      ],
      oldHeight: { top: 0, left: 0 },
      newHeight: { top: 0, left: "50%" },
    });
    const resize = () => {
      data.heightArr = [
        { top: "0px", left: 0 },
        { top: "0px", left: "50%" },
      ];
      data.oldHeight = { top: 0, left: 0 };
      data.newHeight = { top: 0, left: "50%" };
    };
    const getHeight = () => {
      let arr = document.querySelectorAll("#goodList .good-item");
      let oldHeight;
      let newHeight;
      let tag = 10;
      if (arr.length > 2) {
        oldHeight = data.oldHeight.top
          ? data.oldHeight
          : { top: arr[0].offsetHeight, left: 0 };
        newHeight = data.newHeight.top
          ? data.newHeight
          : { top: arr[1].offsetHeight, left: "50%" };
      }else{
          oldHeight = arr[0]
          ?{ top: arr[0].offsetHeight, left: 0 }
          : data.oldHeight;
        newHeight = arr[1]
          ? { top: arr[1].offsetHeight, left: "50%" }
          : data.newHeight;
      }

      for (let i = data.heightArr.length; i < arr.length; i++) {
        if (oldHeight.top > newHeight.top) {
          data.heightArr.push( {
            top: newHeight.top + tag + "px",
            left: newHeight.left,
          });
          newHeight.top += arr[i].offsetHeight + tag;
        } else {
          data.heightArr.push( {
            top: oldHeight.top + tag + "px",
            left: oldHeight.left,
          });
          oldHeight.top += arr[i].offsetHeight + tag;
        }
      }
      data.oldHeight = oldHeight;
      data.newHeight = newHeight;
    };
    return { ...toRefs(data), ...toRefs(props), getHeight, resize };
  },
};
</script>
<style lang="scss" scoped>
.good-list {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  position: relative;
}
.good-item {
  width: 50%;
  box-sizing: border-box;
  animation: jello-horizontal 1s both;
  position: absolute;
  transition: all 1s;
}
@keyframes jello-horizontal {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
</style>